<template>
  <a-modal
    v-model:open="visibleModal"
    centered
    width="416px"
    :title="title"
    :mask-closable="false"
    :body-style="{ 'padding-bottom': '0' }"
    :ok-text="okText"
    :ok-button-props="{
      loading: loading
    }"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="formLoading" tip="加载中">
      <a-form ref="dataSetFormRef" :model="formState" name="basic" layout="vertical" :rules="rules">
        <a-form-item label="数据集名称" name="name">
          <a-input v-model:value="formState.name" v-trim placeholder="请输入数据集名称" :maxlength="200" />
        </a-form-item>
        <a-form-item label="数据集描述" name="describe">
          <a-textarea v-model:value="formState.describe" v-trim :rows="4" :maxlength="200" show-count placeholder="请输入数据集描述" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script setup lang="ts">
  import { FormInstance } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { reactive, ref } from 'vue'

  import { validateBitLen, validateDirName } from '@/utils'

  export interface DataSetFormProps {
    title?: string
    okText?: string
    loading?: boolean
    formLoading?: boolean
  }

  export interface DataSetFormState {
    name?: string
    describe?: string
    id?: string
  }

  export type FormType = 'add' | 'edit'

  withDefaults(defineProps<DataSetFormProps>(), {
    title: '创建数据集',
    okText: '创建',
    loading: false,
    formLoading: false
  })

  const emits = defineEmits<{
    (e: 'onOk', type: FormType, data: DataSetFormState): void
    (e: 'onCancel'): void
  }>()

  const type = ref<FormType>('add')
  const visibleModal = ref(false)
  const dataSetFormRef = ref<FormInstance>()
  const formState = reactive<DataSetFormState>({
    name: '',
    describe: '',
    id: ''
  })

  const rules: Record<string, Rule[]> = {
    name: [
      { required: true, message: '请输入数据集名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ]
  }

  const handleOk = async () => {
    try {
      await dataSetFormRef.value?.validate()
      emits('onOk', type.value, formState)
    } catch (error) {
      console.error(error)
    }
  }

  const handleCancel = () => {
    resetFields()
    emits('onCancel')
  }

  const resetFields = () => {
    dataSetFormRef.value?.resetFields()
    formState.name = ''
    formState.describe = ''
    formState.id = ''
  }

  defineExpose({
    open: (_type: FormType, data?: DataSetFormState) => {
      visibleModal.value = true
      type.value = _type
      _type === 'edit' && Object.assign(formState, data)
    },
    close: () => {
      resetFields()
      visibleModal.value = false
    }
  })
</script>
